package com.rickpan.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * 阿里云OSS工具类
 * 用于文件上传到阿里云对象存储
 */
@Component
public class AliOssUtil {
    
    // 阿里云OSS配置信息
    public static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
    public static final String ACCESS_KEY_ID = "LTAI5t6HvpjZMcJjRca9Y53E";
    public static final String ACCESS_KEY_SECRET = "7sCMbNEPCTJ5r6P1sZKfTNiNtNKowW";
    public static final String BUCKET_NAME = "big-event-rick";
    
    /**
     * 上传文件到阿里云OSS
     * 
     * @param objectName 对象名称（文件在OSS中的路径和名称）
     * @param inputStream 文件输入流
     * @return 文件的访问URL
     * @throws Exception 上传失败时抛出异常
     */
    public static String uploadFile(String objectName, InputStream inputStream) throws Exception {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        String url = "";
        
        try {
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, objectName, inputStream);
            
            // 上传文件
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            
            // 构建文件访问URL
            url = "https://" + BUCKET_NAME + "." + ENDPOINT.substring(ENDPOINT.lastIndexOf("/") + 1) + "/" + objectName;
            
        } catch (OSSException oe) {
            System.err.println("OSS服务异常:");
            System.err.println("Error Message: " + oe.getErrorMessage());
            System.err.println("Error Code: " + oe.getErrorCode());
            System.err.println("Request ID: " + oe.getRequestId());
            System.err.println("Host ID: " + oe.getHostId());
            throw new Exception("OSS上传失败: " + oe.getErrorMessage());
        } catch (ClientException ce) {
            System.err.println("OSS客户端异常:");
            System.err.println("Error Message: " + ce.getMessage());
            throw new Exception("OSS客户端错误: " + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        
        return url;
    }
    
    /**
     * 生成头像文件名
     * 格式: avatar_{userId}_{timestamp}.{extension}
     * 
     * @param userId 用户ID
     * @param originalFilename 原始文件名
     * @return 生成的对象名称
     */
    public static String generateAvatarObjectName(Long userId, String originalFilename) {
        // 获取文件扩展名
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        
        // 生成唯一的文件名
        long timestamp = System.currentTimeMillis();
        return "avatars/avatar_" + userId + "_" + timestamp + extension;
    }
}
